const express = require("express");
const router = express.Router();
const dbCongif = require('../../config/dbconfig')

// router.get('/list', (req, res) => {
//   console.log(req.query,556);
//   let { pageNum, pageSize, type} = req.query
//   // 查列表
//   let sql = `select * from goods_table where type like ? limit ?,?`
//   let sqlArr = ['%'+type+'%',(pageNum-1)*pageSize,parseInt(pageSize)]
//   let sqlTotal = `select count(*) as total from goods_table where type like ? `
//   let sqlTotalArr = ['%'+type+'%']
//   let callBack = (err,results)=>{
//     if (err) {
//       console.log('连接失败')
//     } else {
//       let data = {
//         goodsList: results,
//         total: total,
//         success: true,
//         message: '加载成功'
//       }
//       res.send(data)
//     }
//   }
//   let total = 0
//   dbCongif.sqlConnect(sqlTotal,sqlTotalArr,(err,res)=>{
//     total = res[0].total
//     dbCongif.sqlConnect(sql,sqlArr,callBack)
//   })
// })

//查询商品列表(封装方法)
router.get('/goods/list', (req, res,next) => {
  let queryList = ['username','realname','cellphone','depName','type','status'] //能搜索的参数
  // 查总数
  let sqlTotal = `select count(*) as total from goods_table `
  let sqlTotalArr = []

  // 查列表
  let sql = `select * from goods_table `
  let sqlArr = []
  // 遍历参数
  for (let key in req.query) {
    // 判断是否为可搜索参数
    if (queryList.some(i=>i==key)) {
      if (sqlArr.length == 0) {
        sql += `where ${key} like ? `
        sqlTotal += `where ${key} like ? `
      } else {
        sql += `and ${key} like ? `
        sqlTotal += `and ${key} like ? `
      }
      sqlArr.push("%"+req.query[key]+"%")
      sqlTotalArr.push("%"+req.query[key]+"%")
    }
  }
  if (req.query.pageNum || req.query.pageSize) {
    let pageNum = req.query.pageNum || 1
    let pageSize = req.query.pageSize || 10
    sql += 'limit ?,?'
    sqlArr.push((pageNum-1)*pageSize,parseInt(pageSize))
  }
  let total = 0
  let callBack = (err,results)=>{
    if (err) {
      console.log('连接失败')
    } else {
      let data = {
        data: results,
        total: total,
        success: true,
        message: '加载成功'
      }
      res.send(data)
    }
  }
  dbCongif.sqlConnect(sqlTotal,sqlTotalArr,(err,res)=>{
    total = res[0].total
    dbCongif.sqlConnect(sql,sqlArr,callBack)
  })
})

module.exports = router;